//
//  YYOrderDetailViewController.m
//  FD
//
//  Created by xiaofang wang on 2019/2/12.
//  Copyright © 2019年 ZhiYuan Network. All rights reserved.
//



#import "YYOrderDetailViewController.h"

//复用
#import "WSOrderDetailTableViewProxy.h" //tableView代理方法封装
//model
#import "WSOrderCanPinMsgModel.h" //餐品信息
#import "WSOrderMsgModel.h" //2019-2-13footerView中的tableView的cell的model
//view
#import "WSOrderDetailCell.h" //cell
#import "WSOrderDetailSectionHeaderView.h"
#import "XLAlertView.h" //支付弹框
//工具类
#import "WSOrderDetailDataResolveTool.h"
#import "FDSystemTool.h" //打电话
#import "FDPaytypeAlertTool.h" //支付弹框封装tool


//controller
#import "WSPayUrlViewController.h"//支付VC
#import "EvaluateController.h" //评价VC


//view
#import "YuYueDetailHeaderView.h"
#import "YuYueDetailFooterView.h" //(头:145 + cell:44*5 + 尾:60)


@interface YYOrderDetailViewController ()<YuYueDetailFooterViewDelegate>
/**tableView*/
@property (nonatomic, strong) UITableView *tableView;
/**proxy*/
@property (nonatomic, strong) WSOrderDetailTableViewProxy *tvProxy;
/**头*/
@property (nonatomic, strong) YuYueDetailHeaderView *headerView;
/**尾*/
@property (nonatomic, strong) YuYueDetailFooterView *footerView;

//2019-2-13单独记录订单状态和订单id
/**订单状态*/
@property (nonatomic, strong) NSNumber *tempStatus;
/**订单id*/
@property (nonatomic, copy) NSString *tempOrderId;
/**商家电话*/
@property (nonatomic, copy) NSString *tempShopPhone;
/**支付方式*/
@property (nonatomic, strong ) NSNumber *tempPayType;

@end

@implementation YYOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self requestYuYueOrderDetailWithOrderId:self.userOrderId];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestYuYueOrderDetailWithOrderId:self.userOrderId];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = NSLocalizedString(Home_OrderDetail, @"订单详情");

    self.tableView.frame = self.view.bounds;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
}


#pragma mark - 请求数据
- (void)requestYuYueOrderDetailWithOrderId:(NSString *)userOrderd {
    [FDHttpAPi requestUserYuYueOrderDetailWithUserOrderId:userOrderd successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [self resolvingDataWithDic:responseObjc[@"data"]];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

#pragma mark - 数据解析
- (void)resolvingDataWithDic:(NSDictionary *)dic {
    
    NSArray *proxyDataArr =  [WSOrderDetailDataResolveTool xinResolvingTableViewDataWithDic:dic];
    
    [self resolvingYuYueMenDianDataWithDic:dic];
    [self resolvingCouponFreightSumEtcDataWithDic:dic];
    [self resolvingCanPinMsgDataWithDic:dic];
    
    NSNumber *status = dic[@"status"]; //2019-2-13
    NSString *orderId = dic[@"id"];
    self.tempShopPhone = dic[@"shop"][@"phone"];
    self.tempStatus = status;
    self.tempOrderId = orderId;
    self.tempPayType = dic[@"paymentType"];
    
    
    //回到主线程中刷新数据
    dispatch_async(dispatch_get_main_queue(), ^{
        //1-9 给proxy设置代理
        self.tvProxy.dataArray = proxyDataArr;
        //刷新tableView
        [self.tableView reloadData];
        
        //!!!!:2019-2-13测试
//        self.tempStatus = @(0); //@(4);//评价    //@(0);//支付
//        self.tempPayType = @(0); //0:线上线下   1:线上
        
        [self.footerView updateYuYueDetailFooterViewFooterWithStatus:self.tempStatus paytype:self.tempPayType]; //更新footerView的footerView
    });
}

//解析预约门店信息数据
- (void)resolvingYuYueMenDianDataWithDic:(NSDictionary *)dic {
    
    
    NSString *shopAddress = dic[@"shop"][@"address"]; //店铺地址
    //预约人信息
    NSDictionary *userShopReservationDic = dic[@"userShopReservation"];
    NSNumber *sexNum = userShopReservationDic[@"sex"];
    NSString *consignee = userShopReservationDic[@"consignee"];
    NSString *phone = userShopReservationDic[@"phone"];
    NSString *sexStr = NSLocalizedString(Home_Man, @"先生");
    //国际化性别
    if ([sexNum isEqualToNumber:@(1)]) {
        sexStr = NSLocalizedString(Home_Woman, @"女士");
    }
    //拼接预约人信息
    NSString *personmsg = [NSString stringWithFormat:@"%@ %@ %@",consignee,sexStr,phone];
    
    //更新头部数据
    [self.headerView updateYuYueDetailHeaderViewWithShopAddress:shopAddress personMsg:personmsg];
}


//解析优惠券配送费合计etc
- (void)resolvingCouponFreightSumEtcDataWithDic:(NSDictionary *)dic {
    NSNumber *couponAmount = dic[@"couponAmount"];
    NSNumber *freightAmount = dic[@"freightAmount"];
    
    //1-10已经优惠 = 订单总额-实付金额
    NSNumber *totalAmount = dic[@"totalAmount"];
    NSNumber *actualAmount = dic[@"actualAmount"];
    CGFloat youhui = [totalAmount floatValue] - [actualAmount floatValue];
    
    [self.footerView updateYuYueDetailFooterViewHeaderWithCoupon:couponAmount freight:freightAmount alreadyCoupon:youhui sumPrice:actualAmount];
}

//解析订单信息数据
- (void)resolvingCanPinMsgDataWithDic:(NSDictionary *)dic {
    NSDictionary *userShopReservationDic = dic[@"userShopReservation"];
    NSNumber *number = userShopReservationDic[@"number"]; //1.预约号
    NSString *consignee = userShopReservationDic[@"consignee"]; //2联系人
    NSString *phone = userShopReservationDic[@"phone"]; //3.联系电话
    NSNumber *peopleNumber = userShopReservationDic[@"peopleNumber"]; //4.用餐人数
    NSNumber *sexNum = userShopReservationDic[@"sex"]; //性别
    NSString *sexString = NSLocalizedString(Home_Man, @"先生");
    if ([sexNum isEqualToNumber:@(1)]) {
        sexString = NSLocalizedString(Home_Woman, @"女士");
    }
    
    //国际化
    NSString *yyhStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(Home_YuYueNumber, @"预约号")];
    NSString *lxrStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(Home_contacts, @"联系人")];
    NSString *lxdhStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(Order_ContactPhone, @"联系电话：")];
    NSString *ycrsStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(Home_have_dinner_number, @"用餐人数")];
    NSString *yyxxStr = NSLocalizedString(Home_YuYueMsg, @"预约信息");
    NSArray *arr = @[@{@"title":yyxxStr,@"content":@""},
                     @{@"title":yyhStr,@"content":number},
                     @{@"title":lxrStr,@"content":[NSString stringWithFormat:@"%@%@",consignee,sexString]},
                     @{@"title":lxdhStr,@"content":phone},
                     @{@"title":ycrsStr,@"content":peopleNumber}
                     ];
    
    //转换成模型
    NSMutableArray *tempArrM = [NSMutableArray array];
    for (NSDictionary *innerDic in arr) {
        WSOrderMsgModel *model = [WSOrderMsgModel mj_objectWithKeyValues:innerDic];
        [tempArrM addObject:model];
    }
    
    //赋值
    [self.footerView updateYuYueDetailFooterViewWithDataArray:[tempArrM copy]];
}


#pragma mark - YuYueDetailFooterViewDelegate 底部按钮交互
- (void)clickYuYueDetailFooterBtnActionType:(YuYueDetailFooterViewActionType)actionType {
    if (actionType == YuYueDetailFooterViewActionLeft) {
        FDLog(@"左边:%ld",(long)YuYueDetailFooterViewActionLeft);
        [FDSystemTool fd_makePhone:self.tempShopPhone];
        
    }else if(actionType == YuYueDetailFooterViewActionRight) {
        FDLog(@"右边:%ld",(long)YuYueDetailFooterViewActionRight);
        
        if ([self.tempPayType isEqualToNumber:@(0)] && [self.tempStatus isEqualToNumber:@(0)]) { //立即支付:弹框2个支付方式
            [self alertTwoPayType];
        }else if ([self.tempPayType isEqualToNumber:@(1)] && [self.tempStatus isEqualToNumber:@(1)]) { //立即支付:弹框1个支付方式
            [self alertOnePayType];
        }else if([self.tempStatus isEqualToNumber:@(4)]) {
            EvaluateController *evaluateVC = [[EvaluateController alloc] init];
            evaluateVC.userOrderId = self.tempOrderId;
            evaluateVC.fdDeliveryType = FDDeliveryTypeMenDianYuYue; //门店预约评价
            [self.navigationController pushViewController:evaluateVC animated:YES];
        }else {
            FDLog(@"自提其他状态不做处理:%@--%@",self.tempStatus,self.tempPayType);
        }
    }
}

//!!!!:封装测试
- (void)alertTwoPayType {
    [FDPaytypeAlertTool showAlertTwoPaytypePayOnlineBlock:^{
        [self requestPayOnline];
    } offlineBlock:^{
        [self requestPayOffline];
    }];
}

- (void)alertOnePayType {
    [FDPaytypeAlertTool showAlertOnePayTypeOnlinePayBlock:^{
        [self requestPayOnline];
    }];
}

//!!!!:支付方式
//线上
- (void)requestPayOnline {
    [FDHttpAPi requestPayOnlineWithOrderId:self.tempOrderId successBlock:^(id responseObjc) {
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSString *urlStr = responseObjc[@"data"][@"url"];
            WSPayUrlViewController *payVC = [[WSPayUrlViewController alloc] init];
            payVC.payUrl = urlStr;
            [self.navigationController pushViewController:payVC animated:YES];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

//线下 点击“线下支付”按钮，调用接口(88号)：/user/order/payment/offline 接口调用成功后，刷新当前订单列表即可
- (void)requestPayOffline {
    [FDHttpAPi requestPayOfflineWithOrderId:self.tempOrderId successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            
            //刷新列表
            [self requestYuYueOrderDetailWithOrderId:self.tempOrderId];
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}


#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:(CGRectZero) style:(UITableViewStyleGrouped)];
        //设置代理
        _tableView.delegate = self.tvProxy;
        _tableView.dataSource = self.tvProxy;
        
        //取消线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册cell
        [_tableView registerClass:[WSOrderDetailCell class] forCellReuseIdentifier:@"WSOrderDetailCell"];
        [_tableView registerClass:[WSOrderDetailSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"WSOrderDetailSectionHeaderView"]; //sectionHeaderView
    }
    return _tableView;
}

- (WSOrderDetailTableViewProxy *)tvProxy {
    if (!_tvProxy) {
        _tvProxy = [[WSOrderDetailTableViewProxy alloc] init];
    }
    return _tvProxy;
}

- (YuYueDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[YuYueDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 130)];
    }
    return _headerView;
}

- (YuYueDetailFooterView *)footerView {
    if (!_footerView) {
        //(头:145 + cell:44*5 + 尾:60)
        _footerView = [[YuYueDetailFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 145+50*5+60)];
        _footerView.delegate = self; //设置代理 YuYueDetailFooterViewDelegate
    }
    return _footerView;
}

@end

